import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

/**
* @description: 763. 划分字母区间
* @author hewei
* @date 2022/8/22 16:17
* @version 1.0
*/

public class PartitionLabels {

    public List<Integer> partitionLabels1(String s) {
        int[] temp = new int[26];
        for (int i = 0; i < s.length(); i++) {
            temp[s.charAt(i) - 'a']++;
        }
        char[] chars = s.toCharArray();
        HashSet<Character> set = new HashSet<>();
        List<Integer> ans = new ArrayList<>();
        int sum = 0;
        for (int i = 0; i < chars.length; i++) {
            if (set.isEmpty() && i != 0) {
                ans.add(i - sum);
                sum = i;
            }
            set.add(chars[i]);
            temp[chars[i] - 'a']--;
            if (temp[chars[i] - 'a'] == 0) set.remove(chars[i]);
        }
        ans.add(chars.length - sum);
        return ans;
    }

    public List<Integer> partitionLabels(String s) {
        int[] temp = new int[26];
        for (int i = 0; i < s.length(); i++) {
            temp[s.charAt(i) - 'a'] = i;
        }
        char[] chars = s.toCharArray();
        int start = 0;
        int end = -1;
        List<Integer> ans = new ArrayList<>();
        for (int i = 0; i < chars.length; i++) {
            end = Math.max(end, temp[chars[i] - 'a']);
            if (i == end) {
                ans.add(end - start + 1);
                start = i + 1;
                end = -1;
            }
        }
        return ans;
    }
}
